package day12.charstream;

import java.io.*;
import java.util.ArrayList;
import java.util.Collections;

/**
 * @author Xiao
 * @date 2021/8/2
 */
public class CharStreamCase02 {
    /**
     * 需求：读取文件中的数据排序后再次写到本地。
     */
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new FileReader(
                "videoPractice\\src\\day12\\charstream\\sort1.txt"));
        BufferedWriter bw = new BufferedWriter(new FileWriter(
                "videoPractice\\src\\day12\\charstream\\sort1.txt"));
//        method1(br, bw,list);
        method2(br, bw);
    }

    private static void method2(BufferedReader br, BufferedWriter bw) throws IOException {
        //创建一个集合，用于接收读取到的字符
        ArrayList<Character> list = new ArrayList<>();
        //读取每一行，用String str接收
        String str;
        while ((str = br.readLine()) != null) {
            //将读取到的每行内容转为字符数组
            char[] chars = str.toCharArray();
            //遍历字符数组，将其中不是空格的内容添加到集合
            for (char ch : chars) {
                if (!String.valueOf(ch).equals(" ")) {
                    list.add(ch);
                }
            }
        }
        //对集合排序
        Collections.sort(list);
        //遍历集合，将排序好的元素依次写出到文件中
        for (Character ch : list) {
            bw.write(ch + " ");
        }
        br.close();
        bw.close();
        System.out.println(list);
    }

    private static void method1(BufferedReader br, BufferedWriter bw) throws IOException {
        ArrayList<Character> list = new ArrayList<>();
        int read;
        while ((read = br.read()) != -1) {
            list.add((char) read);
        }
        Collections.sort(list);
        for (Character ch : list) {
            bw.write(ch);
        }
        br.close();
        bw.close();
        System.out.println(list);
    }
}
